package com.lam.common.components.data.interceptor;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;

import com.lam.common.components.data.annotation.DataInject;
import com.lam.common.exception.BaseException;
import com.lam.common.utils.BeanUtil;
import com.lam.common.utils.CollectionUtil;
import com.lam.common.utils.SpringUtils;
import com.lam.common.utils.StringUtils;
import com.lam.common.utils.sql.SqlUtil;

public class DataInjectScanUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(DataInjectScanUtil.class);
	
	public static void scanTableList(String pattern){
		
		List<Class<?>> list = SpringUtils.scanClass(pattern);
		if(CollectionUtil.isEmpty(list)) {
			return ;
		}
		
		Set<String> tableNameSet = new HashSet<>();
		for (Class<?> clazz : list) {
			List<Field> fieldList = BeanUtil.getBusinessFields(clazz);
			for (Field field : fieldList) {
				DataInject dataInject = AnnotationUtils.getAnnotation(field, DataInject.class);
				if(dataInject != null) {
					if(StringUtils.isNotBlank(dataInject.customSql())) {
						tableNameSet.add(SqlUtil.getTableNameBySql(dataInject.customSql()).toString());
					}else if(StringUtils.isNotBlank(dataInject.tableName())){
						tableNameSet.add(dataInject.tableName());
					}else {
						logger.error("DataInject注解中tableName和customSql至少有一个不能为空！class:{}, field:{}", clazz.getName(), field.getName());
						throw new BaseException("TableName不能为空！");
					}
				}
			}
		}
		addTable(tableNameSet);
	}
	
	private static void addTable(Collection<String> list) {
		for (String table : list) {
			if(StringUtils.isBlank(table)) {
				continue;
			}
			if(table.toLowerCase().contains("select ")) {
				DataInjectMybatisInterceptor.tableNameSet.addAll(SqlUtil.getTableNameBySql(table));
			}else {
				DataInjectMybatisInterceptor.tableNameSet.add(table);
			}
		}
	}

}
